<template>
    <div class="app-container">
      <basic-info-form ref="basicInfo" :info="info" />
      <el-divider id="bomDivider"></el-divider>
      <!--工厂模型数据-->
      <el-col :lg="8" style="padding-right: 2%; border-right: 1px #dcdfe6 solid">
        <div class="head-container1" style="display: flex; justify-content: space-between; margin-bottom: 20px">
          <label style="margin-left: 0px"><i class="el-icon-s-operation"></i>BOM信息</label>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['base:shop:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-delete" size="mini" :disabled="selectValue == ''"
                @click="handleDelete" v-hasPermi="['base:shop:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-dropdown>
                <el-button type="primary" icon="el-icon-d-arrow-right" size="mini">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-col :span="1.5">
                        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                          v-hasPermi="['base:shop:import']">导入</el-button>
                      </el-col>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-col :span="1.5">
                        <el-button type="warning" plain icon="el-icon-download" size="mini" style="margin-top: 10px"
                          @click="handleExport" v-hasPermi="['base:shop:export']">导出</el-button>
                      </el-col>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </div>
        <div class="head-container">
          <el-input v-model="SelectshopName" placeholder="请输入名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="bomOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode"
            :highlight-current="true" :current-node-key="currentLivingId" ref="tree" node-key="id" default-expand-all
            @node-click="handleNodeClick" />
        </div>
      </el-col>
  
      <!--BOM详情展示 / 修改BOM数据-->
      <el-col :lg="15" v-if="selectValue != ''" style="margin-left: 1%">
        <div class="head-container1" style=" display: flex; justify-content: space-between; margin-bottom: 20px; ">
          <label style="margin-left: 0px"><i class="el-icon-edit"></i>BOM详情 / 编辑</label>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain size="mini" @click="submitForm"
                v-hasPermi="['base:shop:add']">保存</el-button>
            </el-col>
          </el-row>
        </div>
        <el-form ref="form" :model="form" :rules="rulesform" label-width="90px" style="margin-right: 0px">
          <el-row :gutter="20">
            <el-col :lg="12">
              <el-form-item label="BOMId" prop="bomId" v-show="false">
                <el-input v-model="form.bomId" placeholder="请输入bom-id(关联bom表)" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="父级BOMId" prop="parentId" v-show="false">
                <el-input v-model="form.parentId" placeholder="请输入父级BOM" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="图文号" prop="photoNum">
                <el-input v-model="form.photoNum" placeholder="请输入图文号" style="width: 280px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="物料编码" prop="materialCode">
                <el-select v-model="form.materialCode" filterable placeholder="请选择物料编码" style="width: 280px"
                  @change="Change">
                  <el-option v-for="item in MESMATERIALOptions" :key="item.materialCode" :label="item.materialCode"
                    :value="item.materialCode">
                    <span style="float: left">{{ item.materialCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="物料名称" prop="materialName">
                <el-input disabled v-model="form.materialName" placeholder="请选择物料编码获取物料名称" style="width: 280px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择类型" style="width: 280px">
                  <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="台套数" prop="setNumber">
                <el-input v-model="form.setNumber" placeholder="请输入台套数" style="width: 280px" type="number" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="材料" prop="stuff">
                <el-input v-model="form.stuff" placeholder="请输入材料" style="width: 280px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="质量(kg)" prop="mass">
                <el-input type="number" v-model="form.mass" placeholder="请输入质量(kg)" style="width: 280px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="总质量(kg)" prop="totalMass">
                <el-input v-model="form.totalMass" placeholder="请输入总质量(kg)" style="width: 280px" type="number" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="图纸版本号" prop="versionNum">
                <el-input v-model="form.versionNum" placeholder="请输入图纸版本号" style="width: 280px" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
  
      <!-- 添加物料清单对话框 -->
      <el-dialog :title="title" :visible.sync="drawer" width="760px" append-to-body>
        <el-form ref="addform" :model="addform" :rules="rulesform" label-width="90px">
          <el-row :gutter="20">
            <el-col :lg="12">
              <el-form-item label="BOMId" prop="bomId">
                <el-input v-model="addform.bomId" style="width: 240px" disabled />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="父级BOMId" prop="parentId">
                <el-input v-model="addform.parentId" style="width: 240px" disabled />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="图文号" prop="photoNum">
                <el-input v-model="addform.photoNum" style="width: 240px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="物料编码" prop="materialCode">
                <el-select v-model="addform.materialCode" filterable placeholder="请选择物料编码" style="width: 240px"
                  @change="Change1">
                  <el-option v-for="item1 in MESMATERIALOptions" :key="item1.materialCode" :label="item1.materialCode"
                    :value="item1.materialCode">
                    <span style="float: left">{{ item1.materialCode }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item1.materialName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="物料名称" prop="materialName">
                <el-input disabled v-model="addform.materialName" placeholder="请选择物料编码获取物料名称" style="width: 240px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="类型" prop="type">
                <el-select v-model="addform.type" placeholder="请选择类型" style="width: 240px">
                  <el-option v-for="dict1 in typeOptions" :key="dict1.dictValue" :label="dict1.dictLabel"
                    :value="dict1.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="台套数" prop="setNumber">
                <el-input v-model="addform.setNumber" placeholder="请输入台套数" style="width: 240px" type="number" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="材料" prop="stuff">
                <el-input v-model="addform.stuff" placeholder="请输入材料" style="width: 240px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="质量(kg)" prop="mass">
                <el-input type="number" v-model="addform.mass" placeholder="请输入质量(kg)" style="width: 240px" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="总质量(kg)" prop="totalMass">
                <el-input v-model="addform.totalMass" placeholder="请输入总质量(kg)" style="width: 240px" type="number" />
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="图纸版本号" prop="versionNum">
                <el-input v-model="addform.versionNum" placeholder="请输入图纸版本号" style="width: 240px" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm1">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
    import { getBom } from "@/api/wuliao/wlbom";
    import { listAllMaterial } from "@/api/wuliao/wuliao";
    import {
      getBomDetail,
      delBomDetail,
      addBomDetail,
      updateBomDetail,
      treeselect,
    } from "@/api/wuliao/info.js";
    import basicInfoForm from "@/views/components/BasicInfoFormTemplete";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
      name: "Bom",
      components: {
        basicInfoForm,
        Treeselect,
      },
      data() {
        return {
          drawer: false,
          SelectshopName: undefined,
          currentLivingId: "",
          // 遮罩层
          loading: true,
          bomId: 0,
          selectValue: "",
          title: "",
          // 表单参数
          info: {},
          rules: {},
          rulesform: {},
          form: {},
          addform: {},
          bomOptions: [],
          MESMATERIALOptions: [],
          typeOptions: [],
          defaultProps: {
            children: "children",
            label: "label",
          },
        };
      },
      watch: {
        // 根据名称筛选部门树
        SelectshopName(val) {
          this.$refs.tree.filter(val);
        },
      },
      created() {
        this.getDicts("mes_bom_type").then((response) => {
          this.typeOptions = response.data;
        });
        // const bomId = this.$route.params && this.$route.params.bomId;
        console.log('this.$route.params',this.$route.query.id);
        const bomId = this.$route.query.id;

        this.bomId = bomId;
        if (bomId) {
          // 获取表详细信息
          getBom(bomId).then((res) => {
            this.info = res.data;
          });
        }
        listAllMaterial().then((res) => {
          this.MESMATERIALOptions = res;
        });
        this.getTreeselect();
      },
      methods: {
        Change(e) {
          // 根据id进行筛选（id是唯一的，如果获取多个，需要自己重新定义筛选条件）
          let item = this.MESMATERIALOptions.filter((options) => {
            return options.materialCode === e;
          });
          this.form.materialName = item[0].materialName;
        },
        Change1(e) {
          // 根据id进行筛选（id是唯一的，如果获取多个，需要自己重新定义筛选条件）
          let item = this.MESMATERIALOptions.filter((options) => {
            return options.materialCode === e;
          });
          this.addform.materialName = item[0].materialName;
        },
        /** 查询工厂模型下拉树结构 */
        getTreeselect() {
          var queryParams = { bomId: this.bomId };
          treeselect(queryParams).then((response) => {
            this.bomOptions = response.data;
            if (this.bomOptions.length > 0) {
              this.currentLivingId = this.bomOptions[0].id;
              this.selectValue = this.currentLivingId;
              this.form = {
                bomId: this.currentLivingId,
              };
              this.$nextTick(function () {
                this.$refs.tree.setCurrentKey(this.currentLivingId);
              });
              this.GetBOMDetail(this.selectValue);
            }
          });
        },
        // 筛选节点
        filterNode(value, data) {
          if (!value) return true;
          return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
          this.selectValue = data.id;
          this.reset();
          this.GetBOMDetail(data.id);
        },
        //获取BOM详情
        GetBOMDetail(item) {
          getBomDetail(item).then((res) => {
            this.form = res.data;
          });
        },
        // BOM状态字典翻译
        bomStatusFormat(row, column) {
          return this.selectDictLabel(this.bomStatusOptions, row.bomStatus);
        },
        // 取消按钮
        cancel() {
          this.drawer = false;
          this.resetaddform();
        },
        // 表单重置
        reset() {
          this.form = {
            id: null,
            bomId: this.bomId,
            parentId: this.selectValue,
            ancestors: null,
            photoNum: null,
            materialName: null,
            materialCode: null,
            setNumber: null,
            stuff: null,
            mass: null,
            totalMass: null,
            versionNum: null,
            changeRecord: null,
            type: null,
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null,
          };
          this.resetForm("form");
        },
        resetaddform() {
          this.addform = {
            id: null,
            bomId: this.bomId,
            parentId: this.selectValue,
            ancestors: null,
            photoNum: null,
            materialName: null,
            materialCode: null,
            setNumber: null,
            stuff: null,
            mass: null,
            totalMass: null,
            versionNum: null,
            changeRecord: null,
            type: null,
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null,
          };
          this.resetForm("addform");
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.ids = selection.map((item) => item.bomId);
          this.single = selection.length !== 1;
          this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
          this.resetaddform();
          this.title = "添加BOM";
          this.drawer = true;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset();
          const bomId = row.bomId || this.ids;
          getBom(bomId).then((response) => {
            this.form = response.data;
            this.open = true;
            this.title = "修改物料清单";
          });
        },
        /** 提交按钮 */
        submitForm() {
          this.$refs["form"].validate((valid) => {
            if (valid) {
              if (this.form.bomId != null) {
                updateBomDetail(this.form).then((response) => {
                  if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getTreeselect();
                  }
                });
              }
            }
          });
        },
        /** 提交按钮 */
        submitForm1() {
          this.$refs["addform"].validate((valid) => {
            if (valid) {
              addBomDetail(this.addform).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getTreeselect();
                }
              });
            }
          });
        },
        handleImport() {
          this.msgSuccess("暂未开通!");
        },
        /** 删除按钮操作 */
        handleDelete() {
          this.$confirm(
            '是否确认删除BOM物料为"' + this.selectValue + '"的数据项?',
            "警告",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(function () {
              return delBomDetail(this.selectValue);
            })
            .then(() => {
              this.getList();
              this.msgSuccess("删除成功");
            })
            .catch(function () { });
        },
        handleView(row) {
          /** 修改按钮操作 */
          const tableId = row.tableId || this.ids[0];
          this.$router.push("/gen/edit/" + tableId);
        },
        /** 导出按钮操作 */
        handleExport() {
          const queryParams = this.queryParams;
          this.$confirm("是否确认导出所有物料清单数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(function () {
              return exportBom(queryParams);
            })
            .then((response) => {
              this.download(response.msg);
            })
            .catch(function () { });
        },
      },
    };
  </script>
  
  <style rel="stylesheet/scss" lang="scss">
   
    #bomDivider {
        margin-top: 0px;
      }
  </style>